﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace _3DTestAPP
{
    public partial class Form1 : Form
    {
        SerialPort comm = new SerialPort();
        public Form1()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            comm.DataReceived += new SerialDataReceivedEventHandler(comm_DataReceived);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            foreach (string p in ports)
            {
                ComPort_ComboBox.Items.Add(p);
            }
            ComPort_ComboBox.SelectedIndex = ComPort_ComboBox.Items.Count > 0 ? 0 : -1;
        }

        private void Connect_Button_Click(object sender, EventArgs e)
        {
            //根据当前串口对象，来判断操作
            if (comm.IsOpen)
            {
                //若已经打开，则关闭
                comm.Close();
            }
            else
            {
                //若关闭，则设置好端口，波特率后打开
                comm.PortName = ComPort_ComboBox.Text;
                comm.BaudRate = int.Parse(ComBaud_ComboBox.SelectedItem.ToString());
                comm.DataBits = 8;
                comm.Parity = 0;
                comm.StopBits = StopBits.One;
                comm.ReadTimeout = 1000;
                try
                {
                    comm.Open();
                }
                catch (System.Exception ex)
                {
                    //捕获到异常信息，创建一个新的comm对象，之前的不能用了。  
                    comm = new SerialPort();
                    //现实异常信息给客户。  
                    MessageBox.Show(ex.Message);
                }
            }
            Connect_Button.Text = comm.IsOpen ? "断开" : "连接";
            Connect_Button.ForeColor = comm.IsOpen ? Color.Red: Color.Blue;
        }

        void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = comm.BytesToRead;
            byte[] buffer = new byte[n];
            comm.Read(buffer, 0, n);
            int US100_Receive;
            for (int i = 0; i < n - 3; i++)
            {
                if (buffer[i] == 0xFF)
                {
                    if ((byte)(buffer[i + 1] ^ buffer[i + 2]) == buffer[i + 3])
                    {
                        US100_Receive = buffer[i + 1] * 100 + buffer[i + 2];
                        US100_TextBox.Text = US100_Receive.ToString();
                        Output_TextBox.AppendText("n:"+n+"  "+US100_Receive.ToString() + "\r\n");
                        Output_TextBox.ScrollToCaret();
                    }
                }
            }
            
        }

    }
}
